package demo.practice.leetcode;

import java.util.Stack;

public class P20 {
    //https://leetcode-cn.com/problems/valid-parentheses/

    public static void main(String[] args) {

    }

    public boolean isValid(String s) {

        Stack<Character> stack= new Stack();
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(c=='{'|| c=='(' || c=='['){
                stack.push(c);
            }else{
                if(stack.isEmpty())
                    return false;
                Character p = stack.pop(); //注意pop之前去判断，因为pop方法在空栈的时候会抛异常
                if(c=='}'&& p!='{' )
                    return false;

                if(c==')' && p!='(' )
                    return false;

                if(c==']'&& p!='[' )
                    return false;

            }
        }

        return stack.isEmpty();
    }


}
